﻿using Helldivers_Alpha.Data;
using Helldivers_Alpha.DataFrom;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Helldivers_Alpha
{
    public partial class Helldivers_Alpha : Form
    {
        public Helldivers_Alpha()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 搓球延迟时间
        /// </summary>
        public static int DelayTime=10;
        private CDD dd;
        System.Timers.Timer Maintimer;
        public bool ISstratRuning = false;
        #region "UI交互相关"
        /// <summary>
        /// 槽位1委托
        /// </summary>
        public delegate void defaultModNO1Handler();
        public static defaultModNO1Handler DH01;
        public static defaultModNO1Handler DH02;
        public static defaultModNO1Handler DH03;
        public static defaultModNO1Handler DH04;
        public static DefaultMod defaultModNO1 = null;
        public static DefaultMod defaultModNO2 = null;
        public static DefaultMod defaultModNO3 = null;
        public static DefaultMod defaultModNO4 = null;

        /// <summary>
        /// 槽位1选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            SupplyStratagemsFrom supplyStratagemsFrom = new SupplyStratagemsFrom(new SupplyStratagems().Data, 1);
            supplyStratagemsFrom.StartPosition = FormStartPosition.Manual;
            supplyStratagemsFrom.Location = new Point(this.Location.X, this.Location.Y + 200);
            supplyStratagemsFrom.Show();
        }
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            SupplyStratagemsFrom supplyStratagemsFrom = new SupplyStratagemsFrom(new SupplyStratagems().Data, 2);
            supplyStratagemsFrom.StartPosition = FormStartPosition.Manual;
            supplyStratagemsFrom.Location = new Point(this.Location.X, this.Location.Y + 200);
            supplyStratagemsFrom.Show();
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
            SupplyStratagemsFrom supplyStratagemsFrom = new SupplyStratagemsFrom(new SupplyStratagems().Data, 3);
            supplyStratagemsFrom.StartPosition = FormStartPosition.Manual;
            supplyStratagemsFrom.Location = new Point(this.Location.X, this.Location.Y + 200);
            supplyStratagemsFrom.Show();
        }

        private void pictureBox4_Click(object sender, EventArgs e)
        {
            SupplyStratagemsFrom supplyStratagemsFrom = new SupplyStratagemsFrom(new SupplyStratagems().Data, 4);
            supplyStratagemsFrom.StartPosition = FormStartPosition.Manual;
            supplyStratagemsFrom.Location = new Point(this.Location.X, this.Location.Y + 200);
            supplyStratagemsFrom.Show();
        }
        private void label4_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 设置槽位1
        /// </summary>
        public void pictureBox1Set()
        {
            pictureBox1.Image = defaultModNO1.Img;
            label1.Text = defaultModNO1.Name;
        }
        public void pictureBox2Set()
        {
            pictureBox2.Image = defaultModNO2.Img;
            label2.Text = defaultModNO2.Name;
        }
        public void pictureBox3Set()
        {
            pictureBox3.Image = defaultModNO3.Img;
            label3.Text = defaultModNO3.Name;
        }
        public void pictureBox4Set()
        {
            pictureBox4.Image = defaultModNO4.Img;
            label4.Text = defaultModNO4.Name;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SetFrom setFrom = new SetFrom();
            setFrom.StartPosition = FormStartPosition.Manual;
            setFrom.Location = new Point(this.Location.X, this.Location.Y + 200);
            setFrom.Show();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
        #endregion
        #region "其他"
        #endregion


        /// <summary>
        /// 初始化事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Helldivers_Alpha_Load(object sender, EventArgs e)
        {
            //载入配置文件
            //延迟时间
            DelayTime = Properties.Settings.Default.DelayTime;
            //是否即挫即丢
            checkBox1.Checked = Properties.Settings.Default.CheckOutRua;


            DH01 = new defaultModNO1Handler(pictureBox1Set);
            DH02 = new defaultModNO1Handler(pictureBox2Set);
            DH03 = new defaultModNO1Handler(pictureBox3Set);
            DH04 = new defaultModNO1Handler(pictureBox4Set);

            //判断系统位数
            bool Is64Bit= Environment.Is64BitOperatingSystem;
            reg_hotkey();//注册快捷键
            dd = new CDD();
            string appfilepath = System.AppDomain.CurrentDomain.BaseDirectory;
            string dllname = "";
            if (Is64Bit)
            {
                dllname = "DD85590.64.dll";
            }
            else
            {
                dllname = "DD85590.32.dll";
            }
            string dllfilepath = appfilepath + dllname;
            System.IO.FileInfo fi = new System.IO.FileInfo(dllfilepath);
            if (!fi.Exists)
            {
                MessageBox.Show("文件丢失，文件不存在");
                return;
            }
            LoadDllFile(dllfilepath);

           
        }

        /// <summary>
        /// Timer类执行定时到点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerUp(object sender, System.Timers.ElapsedEventArgs e)
        {
            //maincheckmove++;
            try
            {
              
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 加载dll
        /// </summary>
        /// <param name="dllfile"></param>
        private void LoadDllFile(string dllfile)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(dllfile);
            if (!fi.Exists)
            {
                MessageBox.Show("文件不存在");
                return;
            }

            int ret = dd.Load(dllfile);
            string dllfiletext = "初始化成功";
            if (ret == -2) { MessageBox.Show("装载库时发生错误"); dllfiletext = "装载库时发生错误"; return; }
            if (ret == -1) { MessageBox.Show("取函数地址时发生错误"); dllfiletext = "取函数地址时发生错误"; return; }
            //if (ret == 0) { MessageBox.Show("非增强模块"); }


            statustext.Text = dllfiletext;

            return;
        }


        #region "热键设置相关代码"
        /// <summary>
        /// 
        /// </summary>
        public void StringToKey(string text,int id)
        {

            string[] result;
            string[] separators = new string[] { " + " };
            result = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            List<KeyModifiers> keyModifiers = new List<KeyModifiers>();
            List<Keys> miankeys = new List<Keys>();
            //Iterate through the keys and find the modifier.
            foreach (string entry in result)
            {
                //Find the Control Key.
                if (entry.Trim() == Keys.Control.ToString())
                {
                    keyModifiers.Add(KeyModifiers.Control);
                }
                else
                //Find the Alt key.
                if (entry.Trim() == Keys.Alt.ToString())
                {
                    keyModifiers.Add(KeyModifiers.Alt);
                }
                else
                //Find the Shift key.
                if (entry.Trim() == Keys.Shift.ToString())
                {
                    keyModifiers.Add(KeyModifiers.Shift);
                }
                else
                {
                    KeysConverter keyconverter = new KeysConverter();
                    var  key = (Keys)keyconverter.ConvertFrom(entry);
                    miankeys.Add(key);
                }
            }
            KeyModifiers Modifier = KeyModifiers.None;
            foreach (var item in keyModifiers)
            {
                Modifier |= item;
            }
            RegisterHotKey(this.Handle, id, KeyModifiers.Control, miankeys.FirstOrDefault());
        }


        [DllImport("user32.dll")]
        public static extern bool RegisterHotKey(
         IntPtr hWnd,
         int id,                            // 热键标识
         KeyModifiers modkey,  //  修改键
         Keys vk                         //  虚键码
        );
        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(
         IntPtr hWnd,              // 窗口句柄 
         int id                          // 热键标识 
        );

        [DllImport("user32.dll")]
        public static extern int GetAsyncKeyState(int Key);

        void reg_hotkey()
        {
            RegisterHotKey(this.Handle, 80, 0, Keys.F5);
         
            //RegisterHotKey(this.Handle, 100, KeyModifiers.Shift | KeyModifiers.Control, Keys.B); //热键为SHIFT+CTRL+B
            //RegisterHotKey(this.Handle, 200, KeyModifiers.Alt, Keys.D0);                                     //热键为Alt+0
        }

        void reg_hotkey_main()
        {
            //RegisterHotKey(this.Handle, 90, KeyModifiers.Control, Keys.Z);
            //RegisterHotKey(this.Handle, 91, KeyModifiers.Control, Keys.X);
            //RegisterHotKey(this.Handle, 92, KeyModifiers.Control, Keys.C);
            //RegisterHotKey(this.Handle, 93, KeyModifiers.Control, Keys.V);
            //RegisterHotKey(this.Handle, 100, KeyModifiers.Control, Keys.Q);
            //RegisterHotKey(this.Handle, 101, KeyModifiers.Control, Keys.D4);
            //RegisterHotKey(this.Handle, 102, KeyModifiers.Control, Keys.D5);
            //RegisterHotKey(this.Handle, 103, KeyModifiers.Control, Keys.D6);
            //RegisterHotKey(this.Handle, 104, KeyModifiers.Control, Keys.D7);
            StringToKey(Properties.Settings.Default.RegistHotKey01,90);
            StringToKey(Properties.Settings.Default.RegistHotKey02, 91);
            StringToKey(Properties.Settings.Default.RegistHotKey03, 92);
            StringToKey(Properties.Settings.Default.RegistHotKey04, 93);
            StringToKey(Properties.Settings.Default.RegistHotKey05, 100);
            StringToKey(Properties.Settings.Default.RegistHotKey06, 101);
            StringToKey(Properties.Settings.Default.RegistHotKey07, 102);
            StringToKey(Properties.Settings.Default.RegistHotKey08, 103);
            StringToKey(Properties.Settings.Default.RegistHotKey09, 104);
        }
        void unreg_hotkey_main()
        {
            UnregisterHotKey(this.Handle, 90);
            UnregisterHotKey(this.Handle, 91);
            UnregisterHotKey(this.Handle, 92);
            UnregisterHotKey(this.Handle, 93);
            UnregisterHotKey(this.Handle, 100);
            UnregisterHotKey(this.Handle, 101);
            UnregisterHotKey(this.Handle, 102);
            UnregisterHotKey(this.Handle, 103);
            UnregisterHotKey(this.Handle, 104);
            //UnregisterHotKey(this.Handle, 200);                     //缷载3个快捷键
        }

        void unreg_hotkey()
        {
            UnregisterHotKey(this.Handle, 80);
            UnregisterHotKey(this.Handle, 90);
            UnregisterHotKey(this.Handle, 91);
            UnregisterHotKey(this.Handle, 92);
            UnregisterHotKey(this.Handle, 93);
            UnregisterHotKey(this.Handle, 100);
            UnregisterHotKey(this.Handle, 101);
            UnregisterHotKey(this.Handle, 102);
            UnregisterHotKey(this.Handle, 103);
            UnregisterHotKey(this.Handle, 104);
            //UnregisterHotKey(this.Handle, 200);                     //缷载3个快捷键
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;                        //0x0312表示用户热键
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    ProcessHotkey(m);                                      //调用ProcessHotkey()函数
                    break;
            }
            base.WndProc(ref m);
        }

        private void ProcessHotkey(Message msg)              //按下设定的键时调用该函数
        {
            switch (msg.WParam.ToInt32())
            {
                case 80:
                    Fun80();
                    break;
                case 90:
                    Fun90();                                                         
                    break;
                case 91:
                    Fun91();                                                         
                    break;
                case 92:
                    Fun92();                                                         
                    break;
                case 93:
                    Fun93();                                                         
                    break;
                case 100:
                    Fun100();
                    break;
                case 101:
                    Fun101();
                    break;
                case 102:
                    Fun102();
                    break;
                case 103:
                    Fun103();
                    break;
                case 104:
                    Fun104();
                    break;
                case 200:
                    Fun200();
                    break;
            }
        }

        /// <summary>
        /// 全系统启用
        /// </summary>
        private void Fun80()
        {
            if (ISstratRuning)
            {

                System.Media.SystemSounds.Asterisk.Play();
                ISstratRuning = false;
                statustext.Text = "关闭";
                unreg_hotkey_main();
                //Maintimer.Stop();
            }
            else
            {

                System.Media.SystemSounds.Hand.Play();
                ISstratRuning = true;
                statustext.Text = "开启";
                reg_hotkey_main();
                ///Maintimer.Start();
            }
        }

        /// <summary>
        /// ctrl+z 第一槽位
        /// </summary>
        private void Fun90()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    if (defaultModNO1!=null)
                    {
                        StartKeyList(defaultModNO1.keyList, Properties.Settings.Default.CheckOutRua);
                    }
                }
            }
        }
        private void Fun91()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    if (defaultModNO2 != null)
                    {
                        StartKeyList(defaultModNO2.keyList, Properties.Settings.Default.CheckOutRua);
                    }
                }
            }
        }
        private void Fun92()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    if (defaultModNO3 != null)
                    {
                        StartKeyList(defaultModNO3.keyList, Properties.Settings.Default.CheckOutRua);
                    }
                }
            }
        }
        private void Fun93()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    if (defaultModNO4 != null)
                    {
                        StartKeyList(defaultModNO4.keyList, Properties.Settings.Default.CheckOutRua);
                    }
                }
            }
        }
        /// <summary>
        /// 玩家救援
        /// </summary>
        private void Fun101()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    StartKeyList(SpecialStratagems.Reinforce.keyList, Properties.Settings.Default.CheckOutRua);
                }
            }
        }
        /// <summary>
        /// 地狱火
        /// </summary>
        private void Fun102()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    StartKeyList(SpecialStratagems.NUX_223_Hellbomb.keyList, Properties.Settings.Default.CheckOutRua);
                }
            }
        }
        /// <summary>
        /// 金属探测器
        /// </summary>
        private void Fun103()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    StartKeyList(SpecialStratagems.ME_1_SnifferMetalDetector.keyList, Properties.Settings.Default.CheckOutRua);
                }
            }
        }
        /// <summary>
        /// sos信标
        /// </summary>
        private void Fun104()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    StartKeyList(SpecialStratagems.Emergency_Beacon.keyList, Properties.Settings.Default.CheckOutRua);
                }
            }
        }
        /// <summary>
        /// 自救  不扔
        /// </summary>
        private void Fun100()
        {
            if (dd.key != null)
            {
                if (ISstratRuning)
                {
                    StartKeyList(SpecialStratagems.Reinforce.keyList, false);
                }
            }

        }

        //增强功能测试
        private void Fun200()
        {
            //窗口句柄。如果为0表示全屏
            IntPtr hwnd = (IntPtr)0;

            hwnd = dd.GetActiveWindow();

            //移动鼠标到指定窗口相对坐标位置，当 hwnd==0时，等同于dd.mov
            dd.MouseMove(hwnd, 100, 100);

            //抓图。保存在 C:\DD Snap 目录
            dd.SnapPic(hwnd, 200, 200, 200, 200);

            //取色
            Int32 clr32 = dd.PickColor(hwnd, 50, 50, 1);
            Color clr = Color.FromArgb(clr32);
            this.BackColor = clr;

        }

        /// <summary>
        /// 处理键盘按键  
        /// </summary>
        /// <param name="rua">是否按了就扔</param>
        private void StartKeyList(List<key> keys, bool rua)
        {
            Task.Factory.StartNew(() => {
                Random randObj = new Random();
                var ctrlkey = (int)System.Windows.Forms.Keys.Control;
                //模拟 系统热键 CTRL
                if (GetAsyncKeyState(ctrlkey) != 0)//按下
                {
                    foreach (var item in keys)
                    {
                        //基础延迟加上随机数
                        System.Threading.Thread.Sleep(DelayTime + randObj.Next(0, 10));
                        switch (item)
                        {
                            case key.上:
                                //模拟w
                                dd.key(302, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(302, 2);
                                break;
                            case key.下:
                                //模拟s
                                dd.key(402, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(402, 2);
                                break;
                            case key.左:
                                //模拟a
                                dd.key(401, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(401, 2);
                                break;
                            case key.右:
                                //模拟d
                                dd.key(403, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(403, 2);
                                break;
                            default:
                                break;
                        }

                    }
                }
                else//没有按
                {
                    dd.key(600, 1);                               
                                                                         //模拟按wasd
                    foreach (var item in keys)
                    {
                        //基础延迟加上随机数
                        System.Threading.Thread.Sleep(DelayTime + randObj.Next(0, 10));
                        switch (item)
                        {
                            case key.上:
                                //模拟w
                                dd.key(302, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(302, 2);
                                break;
                            case key.下:
                                //模拟s
                                dd.key(402, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(402, 2);
                                break;
                            case key.左:
                                //模拟a
                                dd.key(401, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(401, 2);
                                break;
                            case key.右:
                                //模拟d
                                dd.key(403, 1);
                                System.Threading.Thread.Sleep(5);
                                dd.key(403, 2);
                                break;
                            default:
                                break;
                        }

                    }
                    System.Threading.Thread.Sleep(5);
                    //松开ctrl键
                    dd.key(600, 2);
                }
                //见鬼了 10毫秒容易失败  100貌似才能保证扔出去
                System.Threading.Thread.Sleep(DelayTime*10);
                //模拟鼠标左击
                if (rua)
                {
                    dd.btn(1);
                    System.Threading.Thread.Sleep(5);
                    dd.btn(2);
                }
            });
            
        }

        #endregion

        private void label9_Click(object sender, EventArgs e)
        {
           

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.CheckOutRua = checkBox1.Checked;
            Properties.Settings.Default.Save();
        }
        
    }
}
